package com.AEWMS.Servlet.util;

import com.AEWMS.Dao.Admin;
import com.AEWMS.Dao.Parent;
import com.AEWMS.Dao.Student;
import com.AEWMS.Service.AdminService;
import com.AEWMS.Service.ParentService;
import com.AEWMS.Service.StudentService;
import com.AEWMS.Utlis.MailSender;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;

/**
 * @author lhs
 * @create 2021/4/3 15:05
 */
@WebServlet(name = "MailSenderServlet", urlPatterns = "/MailSenderServlet")
public class MailSenderServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String emailTitle = "学业预警系统找回密码";
        String userId = request.getParameter("userid");
        String userType = request.getParameter("userType");
        String identifyCode = getRandomCode();
        //学生找回
        if(userType.equals("student")){
            StudentService ss = new StudentService();
            Student s = ss.findStuNotViewById(userId);
            System.out.println(s);
            ss.closeCon();
            //调用静态方法
            MailSender.sendMail(emailTitle, s.getStudentTel(), "您的验证码是："+identifyCode);
        }
        //管理员老师找回
        if (userType.equals("admin")){
            AdminService as = new AdminService();
            Admin a = as.findAdmById(userId);
            System.out.println(a);
            as.closeCon();
            //调用静态方法
            MailSender.sendMail(emailTitle, a.getAdminTel(), "您的验证码是："+identifyCode);
        }
        //家长找回
        if (userType.equals("parent")){
            ParentService ps = new ParentService();
            Parent p = ps.findChildById(userId);
            System.out.println(p);
            //调用静态方法
            MailSender.sendMail(emailTitle, p.getParentTel(), "您的验证码是："+identifyCode);
            ps.closeCon();
        }
        response.getWriter().println(JSON.toJSONString(identifyCode));
    }

    public static String getRandomCode(){
        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb=new StringBuilder(4);
        for(int i=0;i<4;i++)
        {
            char ch=str.charAt(new Random().nextInt(str.length()));
            sb.append(ch);
        }
        return sb.toString();
    }
}
